<template>
  <header-container :title="projName">
    <template #menu-content>
      <el-menu :default-active="activeKey" :ellipsis="false" mode="horizontal" @select="onMenuSelect">
        <div :key="item.key" v-for="item in menuStore.menuList">
          <SubMenu v-if="item.subMenu && item.subMenu.length > 1" :menuItem="item" />
          <el-menu-item v-else :index="item.key">{{ item.name }}</el-menu-item>
        </div>
      </el-menu>
    </template>
    <template #setting-content>
      <el-dropdown @command="handleProjectCommand">
        <span class="project-list">{{ projName }}<el-icon v-if="projectStore.projectList.length > 0"
            class="el-icon--right">
            <ArrowDown />
          </el-icon></span>
        <template #dropdown v-if="projectStore.projectList.length > 0">
          <el-dropdown-menu>
            <el-dropdown-item v-for="item in projectStore.projectList" :key="item.key" :command="item.key" :disabled="item.name == projName">{{ item.name 
              }}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
    <template #main-content>
      <slot name="main-content"></slot>
    </template>
  </header-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'
import headerContainer from '$widget/header-container/header-container.vue';
import SubMenu from './complex-view/sub-menu/sub-menu.vue'
import { useMenuStore } from '$store/menu'
import { useProjectStore } from '$store/project'

const route = useRoute()
const menuStore = useMenuStore()
const projectStore = useProjectStore()
defineProps({
  projName: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['menu-select'])

const activeKey = ref('')

function setActiveKey() {
  const menuItem = menuStore.findMenuItem({
    key: 'key',
    value: route.query.key
  })
  activeKey.value = menuItem?.key
}

onMounted(() => {
  setActiveKey()
})

watch(() => route.query.key, () => {
  setActiveKey()
})

watch(() => menuStore.menuList, () => {
  setActiveKey()
})

function onMenuSelect(menuKey) {
  const menuItem = menuStore.findMenuItem({
    key: 'key',
    value: menuKey
  })
  emit('menu-select', menuItem)
}

const handleProjectCommand = function(event) {
    const projectItem = projectStore.projectList.find(item => item.key === event);
    if (!projectItem || !projectItem.homePage) { return; }
    const { host } = window.location;
    console.log(`${host}/view/dashboard${projectItem.homePage}`)
    window.location.replace(`http://${host}/view/dashboard${projectItem.homePage}`);
};
</script>
<style scoped lang="less">
:deep(.el-menu--horizontal.el-menu) {
  border-bottom: 0
}
.project-list {
  margin-right: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  outline: none;
  color: var(--el-color-primary);
}
</style>
